const fs = require('fs');

const path = require('path');

const error = require('../../common/error');

const {S_SERIES} = require('../../common/constans');

/**
 * 读取版本记录
 * @param {*} filePath 记录版本json的文件路径
 */
function read(filePath){

  let content=null;

  try {

    content = fs.readFileSync(filePath,{encoding:'utf8'});

    content = JSON.parse(content);

  } catch (e) {

    error("读取"+filePath+"失败，联系作者：" + e.message);

  }

  return content

}

/**
 * 读取版本记录
 * @param {*} mode 模式 s_series 或 p_series
 */
function readVersionRecord(mode){

  let content;

  if(mode === S_SERIES){

    content=read(path.join(__dirname,'../../lib/s_version.json'));

  }else{

    content=read(path.join(__dirname,'../../lib/p_version.json'));

  }

  return content;

}

/**
 * 写入版本方法
 * @param {*} data 版本号
 * @param {*} filePath 文件路径
 */
function write(data,filePath){

  let content = read(filePath);

  content = content ? content : [];

  content.push(data);

  content = JSON.stringify(Array.from(new Set(content)));

  try {

    fs.writeFileSync(filePath,content,'utf8');
    
  } catch (e) {
    
    error("写入"+filePath+"失败，联系作者：" + e.message);

  }

}

/**
 * 写入版本记录
 * @param {*} version 版本号
 * @param {*} mode 模式 s_series 或 p_series
 */
function writeVersionRecord(version,mode){

  if(mode === S_SERIES){

    write(version,path.join(__dirname,'../../lib/s_version.json'));

  }else{

    write(version,path.join(__dirname,'../../lib/p_version.json'));

  }

}

module.exports={

  readVersionRecord,

  writeVersionRecord

}